#include <stdio.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/pem.h>

int main() {
    FILE *crl_file;
    X509_CRL *crl;
    X509_EXTENSION *ext;
    int ext_index;

    // 打开CRL文件
    crl_file = fopen("/home/zhahaobing/ca/crl/crl.pem", "r");
    if (!crl_file) {
        printf("无法打开CRL文件\n");
        return 1;
    }

    // 从文件中读取CRL
    crl = PEM_read_X509_CRL(crl_file, NULL, NULL, NULL);
    fclose(crl_file);
    if (!crl) {
        printf("cannot read CRL file\n");
        return 1;
    }

    // 查找要删除的扩展
    //ext_index = X509_CRL_get_ext_by_NID(crl, NID_crl_number, -1);
    ext_index = OBJ_txt2nid("crlNumber");
    ext_index = X509_CRL_get_ext_by_NID(crl, ext_index, -1);
    
    printf("ext_index=%d\n", ext_index);
    if (ext_index < 0) {
        printf("not found,at line %d!\n", __LINE__);
        return 1;
    }

    // 获取要删除的扩展
    ext = X509_CRL_get_ext(crl, ext_index);

    // 删除扩展
    // X509_CRL_delete_ext(crl, ext_index);
    
    int crit = X509_EXTENSION_get_critical(ext);
    if (crit) {
        printf("Extension with NID %d is critical\n", ext_index);
    } else {
        printf("Extension with NID %d is not critical,crit=%d\n", ext_index, crit);
    }

    if (ext) {
        // 输出扩展项的名称和数据
        printf("扩展项名称：%s\n", OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext))));
        printf("扩展项数据：%s\n", (char *)X509_EXTENSION_get_data(ext)->data);

		ASN1_OCTET_STRING *extData = X509_EXTENSION_get_data(ext);
		int len = extData->length;
		for(int index=0; index < )
    } else {
        printf("CRL 中没有扩展项\n");
    }
    // 释放扩展项内存
    X509_EXTENSION_free(ext);
    ext = NULL;

    // 查找要删除的扩展
    ext_index = X509_CRL_get_ext_by_NID(crl, NID_crl_number, -1);
    printf("ext_index=%d\n", ext_index);
    if (ext_index < 0) {
        printf("not found,at line %d!\n", __LINE__);
        // return 1;
    }

    unsigned char *out = NULL;
    int32_t length = i2d_X509_CRL(crl, &out);
    if (length <= 0) {
        printf("Do i2d_X509_CRL fail!");
        return -1;
    }
    for(int index=0; index < length; index++)
    {
        if(index%16 == 0)
        {
            printf("\n");
        }
        printf("0x%02x, ", out[index]);   
    }

    // // 重新生成CRL
    // crl_file = fopen("new_crl.pem", "w");
    // if (!crl_file) {
    //     printf("can not create CRL file\n");
    //     return 1;
    // }

    // PEM_write_X509_CRL(crl_file, crl);
    // fclose(crl_file);

    // 释放内存
    X509_CRL_free(crl);

    printf("success.\n");

    return 0;
}
